package com.decent.ejfadmin.utils;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;

/**
 * describe:配置文件管理
 *
 * @author 陈豆豆
 * @date 2019/09/07
 */
@Component
public final class PlatConfigUtil {
    private static PropertiesConfiguration config = null;
    private static final Logger LOGGER = LoggerFactory.getLogger(PlatConfigUtil.class);
    private static String cache_key;

    static {
        try {
            String canonicalPath = new File("").getCanonicalPath();
            if (StringUtils.contains(canonicalPath, "tomcats/hyMS/")) {
                cache_key = "official";
            } else {
                cache_key = "sandBox";
            }
        } catch (IOException e) {
            LOGGER.error("获取项目路径异常", e);
            cache_key = "errorLoading";
        }
    }

    /**
     * 获取动态加载config
     *
     * @param fileName 配置文件名
     * @return config
     */
    public static PropertiesConfiguration getConfig(String fileName) {
        try {
            config = new PropertiesConfiguration(fileName);
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        config.setReloadingStrategy(new FileChangedReloadingStrategy());
        return config;
    }

    /**
     * 获取配置文件值
     *
     * @param fileName     配置文件名
     * @param propertyName 配置文件键
     * @return 值
     */
    public static String getProperty(String fileName, String propertyName) {
        Object object = SimpleCacheUtil.getObject(cache_key + fileName + propertyName);
        if (object != null) {
            return (String) object;
        }
        //保存至缓存2分钟
        String property = (String) getConfig(fileName).getProperty(propertyName);
        SimpleCacheUtil.setObject(cache_key + fileName + propertyName, property, 120);
        return property;
    }
}
